<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Renderable\DepartmentUserRenderable;
use App\Repositories\DepartmentRepository;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class DepartmentController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '科室管理';
    public $repository;

    public function __construct(DepartmentRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = $this->repository->adminGrid('id');
        $grid->column('name', __('名称'));
        $grid->column('users', __('成员数量'))->display(function () {
            return $this->users->count();
        })->modal(DepartmentUserRenderable::class);
        $grid->column('created_at', __('创建时间'));
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
        $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
            $actions->disableDeleteAndHodeSelectAll();
        });
        $grid->disableFilter();
        $grid->disableExport();
        $grid->quickSearch(['name'])->placeholder('关键字');
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = $this->repository->form();

        $form->text('name', __('Department'));
        $form->saving(function (Form $form) {
            if ($form->name != $form->model()->name) {
                $res = $this->repository->newQuery()->where('name', $form->name)->count();
                if ($res) {
                    return back()->withInput()->withErrors([
                        'name' => '部门已存在，添加重复'
                    ]);
                }
            }
        });

        return $form;
    }
}
